<?php
class Services_Ebay_Case extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
			    # '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'services_ebay_case',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */

	static function getUserCases($shop_ids, $start_time, $end_time)
	{
		foreach ($shop_ids as $s)
		{
			$shop_cases = array();
			$token = Shop_API_Ebay::find('shop_id=?', $s)->asArray()->getOne();
			if ($token)
			{
				$ps = 200;
				$cp = 0;
				$total_entries = 1;
				$header = array(
					'X-EBAY-SOA-SECURITY-TOKEN: ' . $token['token'],
					'X-EBAY-SOA-OPERATION-NAME: getUserCases'
				);
				while ($ps * $cp < $total_entries)
				{
					$cp++;
					$xml ='<?xml version="1.0" encoding="utf-8"?>';
					$xml .='<getUserCases xmlns="http://www.ebay.com/marketplace/resolution/v1/services">';
					$xml .='  <paginationInput>';
					$xml .='    <entriesPerPage>' . $ps . '</entriesPerPage>';
					$xml .='    <pageNumber>' . $cp. '</pageNumber>';
					$xml .='  </paginationInput>';
					$xml .='  <creationDateRangeFilter>';
					$xml .='    <fromDate>' . $start_time . '</fromDate>';
					$xml .='    <toDate>' . $end_time . '</toDate>';
					$xml .='  </creationDateRangeFilter>';
					$xml .='</getUserCases>';
					$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_case_uri'), $header, $xml, 'getUserCases', $cp);
					if ($result['ack'] == SUCCESS)
					{
						$response = simplexml_load_string($result['data']);
						if ($response && $response->ack == 'Success')
						{
							$total_entries = (string)$response->paginationOutput[0]->entriesPerPage[0];
							$current_page_cases = Helper_BSS_XML::ebayXMLTocasesArray($token['shop_id'], $response);
							$shop_cases = array_merge($shop_cases, $current_page_cases);
						}
					}
					else
					{
						return array('ack' => FAILURE, 'message' => $result['message']);
					}
				}
				$import_result = Services_Ebay_Case::import($shop_cases);
			}
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	static function getEBPCaseDetail($case)
	{
		if (in_array($case['type'], array(Q::ini('custom_flag/services_ebay_case_type/EBP_INR/value'), Q::ini('custom_flag/services_ebay_case_type/EBP_SNAD/value'))))
		{
			$token = Shop_API_Ebay::find('shop_id=?', $case['shop_id'])->asArray()->getOne();
			if ($token && $case)
			{
				$header = array(
					'X-EBAY-SOA-SECURITY-TOKEN: ' . $token['token'],
					'X-EBAY-SOA-OPERATION-NAME: getEBPCaseDetail'
				);
				$xml = '<?xml version="1.0" encoding="utf-8"?>';
				$xml .='<getEBPCaseDetailRequest xmlns="http://www.ebay.com/marketplace/resolution/v1/services">';
				$xml .='  <caseId>';
				$xml .='    <id>' . $case['case_id'] .  '</id>';
				$xml .='    <type>' . Helper_BSS_Normal::getIniOne('services_ebay_case_type', 'value', $case['type'], 'name') . '</type>';
				$xml .='  </caseId>';
				$xml .='</getEBPCaseDetailRequest>';
				$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_case_uri'), $header, $xml, 'getEBPCaseDetail');
				if ($result['ack'] == SUCCESS)
				{
					$response = simplexml_load_string($result['data']);
					if ($response && $response->ack == 'Success')
					{
						$type_status = Q::ini('custom_flag/services_ebay_case_type/' . (string)$response->caseSummary[0]->caseId[0]->type[0] . '/status_name');
						$status = (string)$response->caseSummary[0]->status[0]->$type_status;
						$transaction_time = date('Y-m-d H:i:s', strtotime((string)$response->caseSummary[0]->item[0]->transactionDate[0]));
						$update_time = date('Y-m-d H:i:s', strtotime((string)$response->caseSummary[0]->lastModifiedDate[0]));
						$reason = isset($response->caseDetail[0]->openReason[0]) ? (string)$response->caseDetail[0]->openReason[0] : NULL;
						$expectation = (string)$response->caseDetail[0]->initialBuyerExpectationDetail[0]->description[0];
						QDB::getConn()->execute('update services_ebay_case set status=\'' . $status . '\',transaction_time=\'' . $transaction_time . '\',update_time=\'' . $update_time . '\',reason=\'' . $reason . '\',expectation=\'' . $expectation . '\' where id=' . $case['id']);
						$detail = Helper_BSS_XML::ebayXMLTocaseDetailArray($case['id'], $response);
						Services_Ebay_Case_Response::create($detail);
						return array('ack' => SUCCESS, 'message' => '');
					}
					else
					{
						return array('ack' => FAILURE, 'message' => isset($response->errorMessage[0]->error[0]->message[0]) ? (string)$response->errorMessage[0]->error[0]->message[0] : '');
					}
				}
				else
				{
					return array('ack' => FAILURE, 'message' => $result['message']);
				}
			}
		}
	}
	
	static function import($cases)
	{
		foreach ($cases as $c)
		{
			$case = Services_Ebay_Case::find('case_id=?', $c['case_id'])->getOne();
			$listing = Online_Ebay_listing::find('item_id=?', $c['shop_item_id'])->asArray()->getOne();
			if (empty($case['id']))
			{
				$case = new Services_Ebay_Case();
				$case->case_id = $c['case_id'];
				$case->shop_item_id = $c['shop_item_id'];
				$case->type = $c['type'];
				$case->shop_id = $c['shop_id'];
				$case->buyer = $c['buyer'];
				$case->currency_id = isset($listing['currency_id']) ? $listing['currency_id'] : '';
				$case->amount = $c['amount'];
				$case->quantity = $c['quantity'];
				$case->create_time = $c['create_time'];
			}
			$case->status = $c['status'];
			$case->update_time = $c['update_time'];
			$case->save();
			$caes = Services_Ebay_Case::find('case_id=?', $c['case_id'])->asArray()->getOne();
			if (empty($case['transaction_time']))
			{
				Services_Ebay_Case::getEBPCaseDetail($case);
			}
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	static function search($condition, $cp, $ps)
	{
		$columns = array(
			'services_ebay_case.*',
			'shop.name as shop_name',
			'currency.symbol as currency_symbol'
		);
		$where = Services_Ebay_Case::buildSearchWhere($condition);
		$select = Services_Ebay_Case::find($where)
			->joinLeft('shop', '', 'services_ebay_case.shop_id=shop.id')
			->joinLeft('currency', '', 'currency.id=services_ebay_case.currency_id')
			->setColumns($columns)->order('services_ebay_case.update_time desc');
		if ($cp == 0 && $ps == 0)
		{
			$pagination = array();
		}
		else
		{
			$select->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$case = $select->asArray()->getAll();
		return array(
			'ack' => SUCCESS,
			'message' => '',
			'data' => $case,
			'pagination' => $pagination
		);
	}
	
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if (isset($condition['shop_user_mapping']))
		{
			$where .= ' and services_ebay_case.shop_id in (\'' . implode('\',\'', $condition['shop_user_mapping']) . '\')';
		}
		if ( ! empty($condition['begin_create_time']))
		{
			$where .= ' and services_ebay_case.create_time>=\'' . $condition['begin_create_time'] . '\'';
		}
		if ( ! empty($condition['end_create_time']))
		{
			$where .= ' and services_ebay_case.create_time<=\'' . $condition['end_create_time'] . '\'';
		}
		if ( ! empty($condition['begin_update_time']))
		{
			$where .= ' and services_ebay_case.update_time>=\'' . $condition['begin_update_time'] . '\'';
		}
		if ( ! empty($condition['end_update_time']))
		{
			$where .= ' and services_ebay_case.update_time<=\'' . $condition['end_update_time'] . '\'';
		}
		if ( ! empty($condition['case_id']))
		{
			$where .= ' and services_ebay_case.case_id=\'' . $condition['case_id'] . '\'';
		}
		if ( ! empty($condition['buyer']))
		{
			$where .= ' and services_ebay_case.buyer=\'' . $condition['buyer'] . '\'';
		}
		if (isset($condition['shop_ids']))
		{
			$where .= ' and services_ebay_case.shop_id in (\'' . implode('\',\'', $condition['shop_ids']) . '\')';
		}
		if (isset($condition['type']))
		{
			$type_filter = '0';
			foreach (Q::ini('custom_flag/services_ebay_case_type') as $t)
			{
				if (isset($condition['type'][$t['value']]) && $condition['type'][$t['value']] == $t['value'])
				{
					$type_filter .= ' or services_ebay_case.type=' . $t['value'];
				}
			}
			$where .= ' and (' . $type_filter . ')';
		}
		if (isset($condition['status']))
		{
			$status_filter = '0';
			foreach ($condition['status'] as $s)
			{
				if ($s == 'CLOSED' || $s == 'OTHER_PARTY_RESPONSE_DUE' || $s == 'MY_RESPONSE_DUE')
				{
					$status_filter .= ' or services_ebay_case.status=\'' . $s . '\'';
				}
			}
			$where .= ' and (' . $status_filter . ')';
		}
		return $where;
	}
}